package org.meetunexpectedly.service.login.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IOUtils;
import org.meetunexpectedly.constant.RedisConstant;
import org.meetunexpectedly.entity.vo.Captcha;
import org.meetunexpectedly.entity.user.User;
import org.meetunexpectedly.entity.vo.ForgotPwdVO;
import org.meetunexpectedly.entity.vo.RegisterVO;
import org.meetunexpectedly.exception.BaseException;
import org.meetunexpectedly.limit.RequestLimit;
import org.meetunexpectedly.service.login.CaptchaService;
import org.meetunexpectedly.service.login.LoginService;
import org.meetunexpectedly.service.user.UserService;
import org.meetunexpectedly.util.EncryptionUtil;
import org.meetunexpectedly.util.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Description: 登录服务实现类
 * @Author: pupil
 * @Date: 2024/08/03 下午 9:26
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private EncryptionUtil encryptionUtil;

    @Override
    @RequestLimit
    public User login(User user) {
        String password = user.getPassword();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        // 根据邮箱从数据库查询用户
        user = userService.getOne(wrapper.eq(User::getEmail, user.getEmail()));
        // 判断用户是否查询成功
        if (ObjectUtils.isEmpty(user)) {
            throw new BaseException("账号错误");
        }
        // 判断输入的密码是否正确
        if (!password.equals(encryptionUtil.decrypt(user.getPassword()))) {
            throw new BaseException("密码错误");
        }

        return user;
    }

    @Override
    public void getCaptcha(HttpServletResponse response, String uuId) throws IOException {
        if (ObjectUtils.isEmpty(uuId)) throw new IllegalArgumentException("uuId不能为空");
        // 设置浏览器不会缓存这个响应，因为验证码有效期只有一段时间
        response.setHeader("Cache-Control", "no-store, no-cache");
        // 设置响应内容的类型
        response.setContentType("image/jpeg");
        // 获取图形验证码
        BufferedImage captcha = captchaService.getCaptcha(uuId);
        // 写入图形验证码
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(captcha, "jpg", out);
        // 安全关闭流
        IOUtils.closeQuietly(out);
    }

    @Override
    public Boolean getCode(Captcha captcha) throws Exception {
        return captchaService.validate(captcha);
    }

    @Override
    public Boolean checkCode(String email, Integer code) {
        if (ObjectUtils.isEmpty(email) || ObjectUtils.isEmpty(code)) {
            throw new BaseException("参数为空");
        }

        Object o = redisCacheUtil.get(RedisConstant.EMAIL_CODE + email);
        if (!code.toString().equals(o)) {
            throw new BaseException("验证码错误");
        }

        return true;
    }

    @Override
    public Boolean register(RegisterVO registerVO) throws Exception {
        // 注册成功后删除图形验证码
        if (userService.register(registerVO)) {
            redisCacheUtil.del(RedisConstant.EMAIL_CODE + registerVO.getEmail());
            return true;
        }
        return false;
    }

    @Override
    public Boolean forgotPassword(ForgotPwdVO forgotPwdVO) {
        return userService.ResetPassword(forgotPwdVO);
    }


}
